package com.onpositive.dataminer.core;

import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.ArrayList;

import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.osgi.service.datalocation.Location;

public class DataProviderConfig {

	public static final String DATAPROVIDER_EXTENSION_POINT = "com.onpositive.dataminer.core.dataProvider";

	protected String extensionId;
	protected String url;
	protected ArrayList<String> scope;
	protected ArrayList<String> toIgnore;

	public DataProviderConfig(String attribute) {
		this.extensionId = attribute;
	}

	public DataProviderConfig() {

	}

	public IDataProvider createProvider()
	{
		IConfigurationElement element = getElement();
		IDataProviderFactory factory;
		try {
			factory = (IDataProviderFactory) element.createExecutableExtension("factory");
			IDataProvider create = factory.create(this);
			return create;
		} catch (CoreException e) {
			
		}		
		return null;
	}

	public String toString() {
		IConfigurationElement element = getElement();
		return element.getAttribute("name");
	}

	protected transient IConfigurationElement el;

	protected IConfigurationElement getElement() {
		if (el != null) {
			return el;
		}
		IConfigurationElement[] configurationElementsFor = Platform
				.getExtensionRegistry().getConfigurationElementsFor(
						DATAPROVIDER_EXTENSION_POINT);
		for (IConfigurationElement e : configurationElementsFor) {
			String attribute = e.getAttribute("id");
			if (attribute != null && attribute.equals(extensionId)) {
				this.el = e;
				return e;
			}
		}
		return null;
	}

	public String getImageId(){
		return getElement().getAttribute("imageId");
	}

	public IDataProviderConfigurator getConfigurator() {
		try {
			
			return (IDataProviderConfigurator) getElement().createExecutableExtension("configurator");
		} catch (CoreException e) {
			
		}
		return null;		
	}
	
	public File getProviderTypeDataArea(){
		Location instanceLocation = Platform.getInstanceLocation();
		try {
			URL dataArea = instanceLocation.getDataArea(extensionId);
			URL fileURL = FileLocator.toFileURL(dataArea);
			File file = new File(fileURL.toURI());
			return file;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		return null;		
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public ArrayList<String> getToIgnore() {
		return toIgnore;
	}

	public void setToIgnore(ArrayList<String> toIgnore) {
		this.toIgnore = toIgnore;
	}
}
